<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>模板管理</el-breadcrumb-item>
      <el-breadcrumb-item>模板管理</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <div class="header-form">
        <!-- 创建或者编辑标题 -->
        <h2 class="header-title">{{ title }}</h2>

        <div>
          <el-button
            type="primary"
            icon="el-icon-view"
            @click="previewDialogVisible = true"
            >预览模板</el-button
          >
          <el-button type="primary" icon="el-icon-message" @click="saveTemplate"
            >保存模板</el-button
          >
        </div>
      </div>

      <h3 class="quest-title">
        <el-input
          class="input_title"
          v-model="templateTitle"
          placeholder="请输入标题"
        ></el-input>
      </h3>

      <div class="quest-list">
        <QuestionEditor
          v-for="(quest, index) in questions"
          :key="quest.id"
          class="quest-box"
          v-model="questions[index]"
          @up="putUpQuest(index)"
          @down="putDownQuest(index)"
          @remove="removeQuest(index)"
        />

        <div class="quest-box quest-box-new" v-if="isShowAddBox">
          <el-button @click="addSingleQuest">单选题</el-button>
          <el-button @click="addMultipleQuest">多选题</el-button>
          <el-button @click="addTextQuest">文本题</el-button>
        </div>

        <el-button
          class="quest-box p-20"
          icon="el-icon-plus"
          @click="showQuestBox"
          >添加问题</el-button
        >
      </div>
    </el-card>

    <!-- 预览模板 -->
    <el-dialog
      title="预览模板"
      :visible.sync="previewDialogVisible"
      width="50%"
      @close="previewDialogClosed"
    >
      <el-card>
        <h3 class="quest-title" style="text-align: center">
          {{ templateTitle }}
        </h3>

        <div class="quest-list">
          <Question
            v-for="quest in questions"
            :key="quest.id"
            class="quest-box"
            :quest="quest"
          />

          <el-button
            type="primary"
            class="quest-box p-20"
            icon="el-icon-upload2"
            >提交</el-button
          >
        </div>
      </el-card>
    </el-dialog>
  </div>
</template>

<script>
import QuestionEditor from "@/components/questionnaire/paperEditor/components/QuestionEditor.vue";
import Question from "@/components/questionnaire/paperEditor/components/Question.vue"; //引入模板模板

const TYPE_SINGLE_CHOICE = 1;
const TYPE_MULTIPLE_CHOICE = 2;
const TYPE_TEXT = 3;

export default {
  components: {
    QuestionEditor,
    Question,
  },
  data() {
    return {
      ...this.$route.query,
      title: "", //新建或者编辑标题
      templateTitle: "", //模板标题
      questions: [], //题目
      listRemoveId: [], //？？？
      isShowAddBox: false,
      previewDialogVisible: false, //预览模板，起初为false

      //模板的请求query
      queryInfo: {
        // query: "", //查询信息
        pageNum: 1, //当前页
        pageSize: 4, //每一页最大数
      },
    };
  },

  mounted() {
    this.init();
  },
  methods: {
    init() {
      switch (this.name) {
        case "新增模板": {
          this.initAdd();
          break;
        }
        case "编辑模板": {
          this.initEdit();
          break;
        }
      }
    },
    initAdd() {
      this.title = "新增模板";
    },
    async initEdit() {
      this.title = "编辑模板";
      const id = this.id + ""; //转变为字符串
      await this.$http({
        method: "post",
        url: "/queryQuestionnairesByQidY",
        data: {
          query: id,
          pageNum: this.queryInfo.pageNum,
          pageSize: this.queryInfo.pageSize,
        },
      }).then((response) => {
        const template = response.data.data.list[0]; //虽然传入list,默认取第一个
        // console.log(template);
        this.templateTitle = template.title;
        var questions = JSON.parse(template.content);
        // console.log(questions);
        this.$nextTick(() => {
          questions.forEach((quest, index) => {
            const data = {
              id: quest.id,
              index: index,
              title: quest.title,
              type: quest.type,
              must: quest.must,
              setIndex: quest.setIndex,
            };

            if (quest.type !== TYPE_TEXT) {
              // const options = this.getOptionsByQuestionId(quest.id);
              var options = quest.options;
              data.options = options.map((option, index) => ({
                id: option.id,
                index: index,
                questionId: option.questionId,
                text: option.text,
              }));
            }

            if (quest.type === TYPE_TEXT) {
              data.tip = quest.tip;
            }
            this.questions.push(data);
            // console.log(quest);
          });
        });
      });
    },

    putUpQuest(index) {
      const questions = this.questions;
      const quest = questions.splice(index, 1)[0];
      questions.splice(index - 1, 0, quest);
      this.resetIndex();
    },
    putDownQuest(index) {
      const questions = this.questions;
      const quest = questions.splice(index, 1)[0];
      questions.splice(index + 1, 0, quest);
      this.resetIndex();
    },
    removeQuest(index) {
      const quest = this.questions.splice(index, 1);
      quest.id && this.listRemoveId.push(quest.id);
      this.resetIndex();
    },
    resetIndex() {
      this.questions.forEach((quest, index) => {
        quest.index = index;
      });
    },

    toCharts(id) {
      this.$router.push({
        name: "charts",
        query: {
          id: id,
        },
      });
    },
    back() {
      this.$router.push({
        name: "home",
      });
    },
    // 保存模板
    async saveTemplate() {
      // let name = window.sessionStorage.getItem("name");
      const confirmResult = await this.$confirm("确认保存模板?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch((err) => err);
      if (confirmResult != "confirm") {
        //取消
        return this.$message.info("已取消保存");
      }

      if (this.name === "新增模板") {
        await this.$http({
          method: "post",
          url: "/createQuestionnaire",
          data: {
            title: this.templateTitle,
            content: JSON.stringify(this.questions),
          },
        }).then((res) => {
          if (res.data.code == "666") {
            // console.log(res);
            this.$message.success(res.data.message);
            this.$router.push("/template");
          } else {
            this.$message.error(res.data.message);
          }
        });
      } else if (this.name === "编辑模板") {
        const id = this.id + "";
        await this.$http({
          method: "post",
          url: "/updateQuestionnaireContent",
          data: {
            qid: id,
            title: this.templateTitle,
            content: JSON.stringify(this.questions),
          },
        }).then((res) => {
          if (res.data.code == "666") {
            this.$message.success(res.data.message);
          } else {
            this.$message.error(res.data.message);
          }
        });
      } else {
        console.log("出现异常");
      }
    },

    //关闭预览界面
    previewDialogClosed() {
      this.previewDialogVisible = false;
    },

    showQuestBox() {
      this.isShowAddBox = true;
    },
    addQuest(type) {
      const data = {
        title: "",
        type: type,
        must: true,
        setIndex: -1, //不知道有啥用
      };

      switch (type) {
        case TYPE_SINGLE_CHOICE:
          //单选题
          data.options = [{ text: "" }, { text: "" }];
          break;
        case TYPE_MULTIPLE_CHOICE:
          //多选题
          data.options = [
            { text: "" },
            { text: "" },
            { text: "" },
            { text: "" },
          ];
          break;
        default:
          //文本题
          data.tip = "请输入答案";
      }

      this.questions.push(data);
      this.resetIndex();
    },
    addSingleQuest() {
      this.addQuest(TYPE_SINGLE_CHOICE);
      this.isShowAddBox = false;
    },
    addMultipleQuest() {
      this.addQuest(TYPE_MULTIPLE_CHOICE);
      this.isShowAddBox = false;
    },
    addTextQuest() {
      this.addQuest(TYPE_TEXT);
      this.isShowAddBox = false;
    },
  },
};
</script>

<style lang="less" scoped>
.quest-list {
  padding: 20px;
  border-top: 1px solid #ccc;
  border-bottom: 1px solid #ccc;
}
.quest-box {
  width: 100%;
  margin-top: 20px;
  border-radius: 0;
}
.quest-box:first-child {
  margin-top: 0;
}
.quest-box-new {
  padding: 20px;
  border: 1px solid #dcdfe6;
  text-align: center;
}
/* 面包屑样式 */
.el-breadcrumb {
  margin-bottom: 15px;
  font-size: 17px;
}
</style>
